<template>
  <d2-container>
    <template slot="header">
      <el-form
        :inline="true"
        :model="queryForm"
        ref="queryForm"
        size="mini"
        style="margin-bottom: -18px;"
      >
        <el-form-item label="所属区域" prop="areaName">
          <el-input
            v-model="queryForm.areaName"
            placeholder="用户"
            style="width: 100px;"
            :disabled="true"
          />
        </el-form-item>

        <!--        <el-form-item label="集中器编号" prop="conncentSerialnumber">-->
        <!--          <el-input-->
        <!--            v-model="queryForm.conncentSerialnumber"-->
        <!--            placeholder="请输入"-->
        <!--            style="width: 100px;"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="集中器名称" prop="conncentName">-->
        <!--          <el-input v-model="queryForm.conncentName" placeholder="请输入" style="width: 100px;" />-->
        <!--        </el-form-item>-->

        <el-form-item>
          <el-button type="primary" @click="handleFormSubmit">
            <d2-icon name="search" />查询
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <split-pane :min-percent="10" :max-percent="20" :default-percent="20" split="vertical">
      <template slot="paneL">
        <my-area-tree @change="onAreaChange" />
      </template>
      <template slot="paneR">
        <d2-crud
          ref="d2Crud"
          selection-row
          @selection-change="handleSelectionChange"
          :columns="columns"
          :data="data"
          :loading="loading"
          :pagination="pagination"
          @pagination-current-change="paginationCurrentChange"
          @dialog-open="handleDialogOpen"
          @dialog-cancel="handleDialogCancel"
          :form-options="formOptions"
          add-title="新增表具"
          :add-template="addTemplate"
          :add-rules="addRules"
          @row-add="handleRowAdd"
          :rowHandle="rowHandle"
          edit-title="修改表具"
          :edit-template="addTemplate"
          :edit-rules="addRules"
          @row-edit="handleRowEdit"
          @row-remove="handleRowRemove"
          @form-data-change="handleFormDataChange"
        >
          <el-button size="mini" slot="header" style="margin-bottom: 5px" @click="addRow">新增</el-button>
          <el-button size="mini" slot="header" style="margin-bottom: 5px" @click="deleteRows">删除</el-button>
          <el-button size="mini" slot="header" style="margin-bottom: 5px">导入添加户号</el-button>
          <el-button size="mini" slot="header" style="margin-bottom: 5px">导入更新户号</el-button>
        </d2-crud>
      </template>
    </split-pane>
  </d2-container>
</template>

<script>
import util from "@/libs/util";
import { Divider } from "element-ui";
import MyAreaTree from "@/components/my-area-tree";
import dayjs from "dayjs";

export default {
  name: "concent",
  components: { MyAreaTree },

  data() {
    return {
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 100,
        total: 0
      },
      queryForm: {
        areaId: 1,
        areaName: "中国",
        conncentSerialnumber: "",
        conncentName: ""
      },
      columns: [
        {
          title: "序号",
          key: "serialNum",
          width: 50
        },
        {
          title: "表计编号",
          key: "serialNumber",
          sortable: true
        },
        {
          title: "设备类型",
          key: "equipmentModelTypeName",
          sortable: true
        },
        {
          title: "imei",
          key: "imei",
          sortable: false
        },
        {
          title: "网络类型",
          key: "equipmentTypeName",
          sortable: true
        },
        {
          title: "IMSI/DEVEUI/SN",
          key: "subInfo",
          sortable: false
        },
        {
          title: "区域组织",
          key: "areaOrgName",
          sortable: true
        },
        {
          title: "供应商",
          key: "sysconfigSupplierName",
          sortable: true
        }
      ],
      data: [],
      treeData: [],
      equipmentTypeList: [],
      props: {
        children: "children",
        label: "name",
        disabled: "disabled",
        value: "id"
      },
      values: [],
      selectParams: {
        size: "mini"
      },
      rowHandle: {
        columnHeader: "操作",
        edit: {
          text: "编辑"
        },
        remove: {
          text: "删除"
        }
      },

      selectionRow: [],
      treeParams: {
        "default-expand-all": true,
        data: [],
        props: {
          children: "children",
          label: "name",
          value: "id"
        }
      },
      formOptions: {
        labelWidth: "120px",
        labelPosition: "left",
        saveLoading: false
      },
      addTemplate: {
        id: {
          title: "id",
          value: "",
          component: {
            show: false
          }
        },
        areaOrg: {
          value: "",
          component: {
            show: false
          }
        },
        serialNumber: {
          title: "表计地址",
          value: "",
          component: {
            disabled: false
          }
        },
        areaOrgName: {
          title: "所属区域",
          value: "",
          component: {
            disabled: true
          }
        },
        imei:{
          title: "IMEI",
          value: "",
        },
        equipmentType: {
          title: "网络类型",
          value: "",
          component: {
            name: "el-select",
            options: []
          }
        },
        deveui: {
          title: "DEVEUI",
          value: "",
          component: {
            show: false
          }
        },
        imsi: {
          title: "IMSI",
          value: "",
          component: {
            show: false
          }
        },
        sn: {
          title: "SN",
          value: "",
          component: {
            show: false
          }
        },
        equipmentModelType: {
          title: "设备类型",
          value: "",
          component: {
            name: "el-select",
            options: []
          }
        },
        installationDate: {
          title: "安装日期",
          value: "",
          component: {
            name: "el-date-picker",
            format: "yyyy-MM-dd"
          }
        },
        handlingDate: {
          title: "搬运日期",
          value: "",
          component: {
            name: "el-date-picker"
          }
        },
        sysconfigSupplier: {
          title: "供应商",
          value: "",
          component: {
            name: "el-select",
            options: []
          }
        }
      },
      addRules: {
        areaOrg: [{ required: true, message: "必填", trigger: "blur" }],
        serialNumber: [{ required: true, message: "必填", trigger: "blur" }],
        imei: [{ required: true, message: "必填", trigger: "blur" }],
        sysconfigSupplier: [
          { required: true, message: "必填", trigger: "blur" }
        ],
        equipmentType: [{ required: true, message: "必填", trigger: "blur" }],
        equipmentModelType: [
          { required: true, message: "必填", trigger: "blur" }
        ],
        connectSimCard: [{ required: true, message: "必填", trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.initData();
    this.getEquipmentType();
    this.handleFormSubmit();
    this.initTree();
    this.getEquipmentmodel();
    this.getSupplier();
  },
  methods: {
    handleFormDataChange({ key, value }) {
      if (key == "equipmentType") {
        // this.$refs.d2Crud.setFormField('equipmentloratype', '')
        // this.$refs.d2Crud.setFormField('equipmentnbtype', '')
        this.$refs.d2Crud.setFormField("deveui", "");
        this.$refs.d2Crud.setFormField("imsi", "");
        this.$refs.d2Crud.setFormField("sn", "");
        // 控制子类型是否显示
        if (value == 1) {
          this.addTemplate.deveui.component.show = true;
          this.addTemplate.sn.component.show = false;
          this.addTemplate.imsi.component.show = false;
        } else if (value == 2) {
          this.addTemplate.imsi.component.show = true;
          this.addTemplate.deveui.component.show = false;
          this.addTemplate.sn.component.show = false;
        } else {
          this.addTemplate.sn.component.show = true;
          this.addTemplate.deveui.component.show = false;
          this.addTemplate.imsi.component.show = false;
        }
      }
    },
    initData() {
      this.$api.admin_equipmentmodel_getEquipmentType().then(res => {
        if (res.equipment) {
          this.equipmentTypeList = res.equipment.map(i => {
            return {
              value: i.value,
              label: i.desc
            };
          });
          this.addTemplate.equipmentType.component.options = this.equipmentTypeList;
        }
      });
    },
    // 获取供应商
    getSupplier() {
      this.$api.admin_supplier_getList().then(res => {
        const options = res.map(i => {
          return {
            value: i.id,
            label: i.supplierName
          };
        });
        this.addTemplate.sysconfigSupplier.component.options = options;
      });
    },
    // 获取所属设备
    getEquipmentmodel() {
      this.$api.admin_equipmentmodel_getList().then(res => {
        const options = res.map(i => {
          return {
            value: i.id,
            label: i.name
          };
        });
        this.addTemplate.equipmentModelType.component.options = options;
      });
    },
    // 获取树
    initTree() {
      this.$api
        .admin_area_getList()
        .then(res => {
          this.treeData = util.getTree(res);
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {});
    },
    handleSelectionChange(selection) {
      this.selectionRow = selection;
    },
    deleteRows() {
      this.$confirm("确定删除吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error"
      }).then(() => {
        this.$api
          .admin_concent_delete(this.selectionRow.map(item => item.id))
          .then(res => {
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.fetchData();
          });
      });
    },
    // 删除row数据
    handleRowRemove({ index, row }, done) {
      this.$api.admin_concent_delete([row.id]).then(res => {
        this.$message({
          message: "删除成功",
          type: "success"
        });
        this.fetchData();
        done();
      });
    },
    handleDialogOpen({ mode, row, index }) {
      if (mode === "edit") {
        this.$api.admin_concent_get({ id: row.id }).then(res => {
          // res.areaOrg = [res.areaOrg]
          res.areaOrgName = row.areaOrgName;
          this.addTemplate.serialNumber.component.disabled = true;
          if (res.equipmentType == 1) {
            this.addTemplate.deveui.component.show = true;
            this.addTemplate.sn.component.show = false;
            this.addTemplate.imsi.component.show = false;
          } else if (res.equipmentType == 2) {
            this.addTemplate.imsi.component.show = true;
            this.addTemplate.deveui.component.show = false;
            this.addTemplate.sn.component.show = false;
          } else {
            this.addTemplate.sn.component.show = true;
            this.addTemplate.deveui.component.show = false;
            this.addTemplate.imsi.component.show = false;
          }
          this.$refs.d2Crud.setFormData(res);
        });
      } else {
        this.addTemplate.serialNumber.component.disabled = false;
      }
    },
    // 增加row数据
    handleRowEdit(row, done) {
      const saveObj = {
        id: row.row.id,
        areaOrg: row.row.areaOrg,
        serialNumber: row.row.serialNumber, // 表计地址
        installationDate:
          row.row.installationDate == ""
            ? ""
            : dayjs(row.row.installationDate).format("YYYY-MM-DD"),
        handlingDate:
          row.row.handlingDate == ""
            ? ""
            : dayjs(row.row.handlingDate).format("YYYY-MM-DD"),
        sysconfigSupplier: row.row.sysconfigSupplier,
        equipmentModelType: row.row.equipmentModelType,
        equipmentType: row.row.equipmentType,
        imei:row.row.imei,
      };
      if (saveObj.equipmentType == 1) {
        saveObj.deveui = row.row.deveui;
      } else if (saveObj.equipmentType == 2) {
        saveObj.imsi = row.row.imsi;
      } else {
        saveObj.sn = row.row.sn;
      }
      this.formOptions.saveLoading = true;
      this.$api
        .admin_concent_update(saveObj)
        .then(res => {
          this.$message({
            message: "保存成功",
            type: "success"
          });
          this.handleFormSubmit();
          done();
        })
        .finally(() => {
          this.formOptions.saveLoading = false;
        });
    },
    // 关闭弹框
    handleDialogCancel(done) {
      done();
    },
    // 新增数据
    addRow() {
      this.$refs.d2Crud.showDialog({
        mode: "add"
      });
      const templateObj = {
        areaOrg: this.queryForm.areaId,
        areaOrgName: this.queryForm.areaName
      };
      this.$refs.d2Crud.setFormData(templateObj);
    },
    handleRowAdd(row, done) {
      const saveObj = {
        id: row.id,
        areaOrg: row.areaOrg,
        serialNumber: row.serialNumber, // 表计地址
        installationDate:
          row.installationDate == ""
            ? ""
            : dayjs(row.installationDate).format("YYYY-MM-DD"),
        handlingDate:
          row.handlingDate == ""
            ? ""
            : dayjs(row.handlingDate).format("YYYY-MM-DD"),
        sysconfigSupplier: row.sysconfigSupplier,
        equipmentModelType: row.equipmentModelType,
        equipmentType: row.equipmentType,
        imei:row.imei,
      };
      if (saveObj.equipmentType == 1) {
        saveObj.deveui = row.deveui;
      } else if (saveObj.equipmentType == 2) {
        saveObj.imsi = row.imsi;
      } else {
        saveObj.sn = row.sn;
      }
      this.formOptions.saveLoading = true;
      this.$api
        .admin_concent_add(saveObj)
        .then(res => {
          this.$message({
            message: "保存成功",
            type: "success"
          });
          this.handleFormSubmit();
          done();
        })
        .finally(() => {
          this.formOptions.saveLoading = false;
        });
    },
    // 获取查询枚举
    getEquipmentType() {
      this.$api
        .admin_concent_getEquipmentType()
        .then(res => {})
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {});
    },
    // 分页操作
    paginationCurrentChange(currentPage) {
      this.pagination.currentPage = currentPage;
      this.fetchData();
    },
    onAreaChange(data, node) {
      this.queryForm.areaId = data.id;
      this.queryForm.areaName = data.name;
      this.handleFormSubmit();
    },
    fetchData() {
      this.loading = true;
      this.$api
        .admin_concent_getPageList({
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          areaOrg: this.queryForm.areaId
        })
        .then(res => {
          this.data = res.data;
          this.pagination.total = res.total;
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleFormSubmit() {
      this.pagination.currentPage = 1;
      this.fetchData();
    }
  }
};
</script>
